package com.hbisedm.interninfosys.intern.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbisedm.interninfosys.commonutils.R;
import com.hbisedm.interninfosys.intern.entity.*;
import com.hbisedm.interninfosys.intern.entity.queryVo.SampleQuery;
import com.hbisedm.interninfosys.intern.entity.queryVo.UserQuery;
import com.hbisedm.interninfosys.intern.entity.vo.StudentInfoVo;
import com.hbisedm.interninfosys.intern.service.*;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sam
 * @since 2020-12-03
 */
@RestController
@RequestMapping("/intern/stu")
public class StuController {
    @Autowired
    IUserService userService;

    @Autowired
    IUserEvaluateService userEvaluateService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    IStuTeachService stuTeachService;

    @Autowired
    IUserRoleService userRoleService;

    @Autowired
    IStuInternshipService stuInternshipService;

    /**
     * 获取学生列表
     */
    @PostMapping("/list/{current}/{limit}")
    public R studentList(@PathVariable long current,
                         @PathVariable long limit,
                         @RequestBody(required = false) UserQuery userQuery) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //type 为 1
        userQueryWrapper.eq("TYPE", 1);
        String name = userQuery.getName();
        String begin = userQuery.getBegin();
        String end = userQuery.getEnd();
        String associationName = userQuery.getAssociationName();
        if(!StringUtils.isEmpty(name)){
            userQueryWrapper.like("OTHERNAME", name);
        }
        if(!StringUtils.isEmpty(begin)){
            userQueryWrapper.ge("CREATE_TIME", begin);
        }
        if(!StringUtils.isEmpty(end)){
            userQueryWrapper.le("CREATE_TIME", end);
        }
        if(!StringUtils.isEmpty(associationName)) {
            String school = "ROLE_学校管理员";
            String intern = "ROLE_企业管理员";
            //通过关联找到企业或者教师对象
            User one = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, associationName));

            //获取角色
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            List<? extends GrantedAuthority> collect = authorities.stream().collect(Collectors.toList());
            GrantedAuthority grantedAuthority = collect.get(0);

            List<Integer> idList = new ArrayList<>();
            if(school.equals(grantedAuthority.getAuthority())) {
                List<User> stuList = userService.list(new QueryWrapper<User>().lambda().eq(User::getDeleted, 0).eq(User::getType, 1).eq(User::getDepartment, one.getDepartment()));
                idList = stuList.stream().map(User::getId).collect(Collectors.toList());
            }else if(intern.equals(grantedAuthority.getAuthority())) {
                List<StuInternship> stuInternshipList = stuInternshipService.list(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getIid, one.getId()));
                idList = stuInternshipList.stream().map(StuInternship::getSid).collect(Collectors.toList());
            }

            userQueryWrapper.in("ID", idList);
        }

        Page<User> userPage = new Page<>(current, limit);
        userService.page(userPage,userQueryWrapper);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        System.out.println("records");
        System.out.println(records);
        return R.ok().data("students", records)
                .data("total",total);
    }

    @GetMapping("/list/{iid}")
    public R studentSampleList(@PathVariable Integer iid) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("TYPE", 1);
        /**
         * 获取已经有实习单位的学生id
         */
        QueryWrapper<StuInternship> stuInternshipQueryWrapper = new QueryWrapper<>();
        stuInternshipQueryWrapper.eq("IID", iid);
        List<StuInternship> list1 = stuInternshipService.list(stuInternshipQueryWrapper);
        List<Integer> hasIIDList = list1.stream().map(StuInternship::getSid).collect(Collectors.toList());
        List<User> list = new ArrayList<>();
        if(hasIIDList.size() >= 1) {
           userQueryWrapper.in("ID", hasIIDList);
           list = userService.list(userQueryWrapper);
       }


        ArrayList<SampleQuery> sampleQueries = new ArrayList<>();
        for (User user : list) {
            SampleQuery sampleQuery = new SampleQuery();
            sampleQuery.setId(user.getId());
            sampleQuery.setValue(user.getOthername());
            sampleQueries.add(sampleQuery);
        }
        return R.ok().data("list", sampleQueries);
    }


    /**
     * 获取已经有教师的学生
     * @param current
     * @param limit
     * @return
     */
    @PostMapping("/noTeachList/{current}/{limit}")
    public R noTeachList(@PathVariable long current,
                         @PathVariable long limit) {
        List<StuTeach> records = stuTeachService.list();
        List<Integer> idList = records.stream().map(StuTeach::getSid).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("TYPE", 1);
        if(!idList.isEmpty()) {
            userQueryWrapper.notIn("ID", idList);
        }
        Page<User> userPage = new Page<>(current, limit);
        userService.page(userPage, userQueryWrapper);
        List<User> userList = userPage.getRecords();
        long total = userPage.getTotal();

        return R.ok()
                .data("students", userList)
                .data("total",total);
    }

    /**
     * 获取没有企业的学生列表
     * @param current
     * @param limit
     * @return
     */
    @PostMapping("/noInternList/{current}/{limit}")
    public R noInternList(@PathVariable long current,
                         @PathVariable long limit) {
        List<StuInternship> records = stuInternshipService.list();
        /**
         * 获取已经有实习单位的学生
         */
        List<Integer> idList = records.stream().map(StuInternship::getSid).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("TYPE", 1);
        if(!idList.isEmpty()) {
            userQueryWrapper.notIn("ID", idList);
        }
        Page<User> userPage = new Page<>(current, limit);
        userService.page(userPage, userQueryWrapper);
        List<User> userList = userPage.getRecords();
        long total = userPage.getTotal();

        return R.ok()
                .data("students", userList)
                .data("total",total);
    }

    @DeleteMapping("/delete/{sid}")
    public R deleteStudent(@PathVariable Integer sid) {
        /**
         * 通过sid 删除学生教师表
         */
        QueryWrapper<StuTeach> stuTeachQueryWrapper = new QueryWrapper<>();
        stuTeachQueryWrapper.eq("SID", sid);
        List<StuTeach> list = stuTeachService.list(stuTeachQueryWrapper);
        boolean remove = true;
        if(list.size() >= 1) {
            remove = stuTeachService.remove(stuTeachQueryWrapper);
        }

        /**
         * 通过sid 删除用户表
         */
        boolean b = userService.removeById(sid);
        if( remove && b) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("/add")
    public R addStudent(@RequestBody User user) {

        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userService.save(user);
        Integer id = user.getId();
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        /**
         * 设置成普通用户 setRoleId（2）
         */
        userRole.setRoleId(2);
        boolean save = userRoleService.save(userRole);
        if(save) {
            return R.ok();
        }
        return R.error();
    }

    @GetMapping("/getStuInfo/{sid}")
    public R getStuInfo(@PathVariable Integer sid) {
        StudentInfoVo studentInfoVo = new StudentInfoVo();
        User byId = userService.getById(sid);
        BeanUtils.copyProperties(byId, studentInfoVo);
        String defaultEvaluate = "--暂未评价--";
        List<UserEvaluate> list = userEvaluateService.list(new QueryWrapper<UserEvaluate>().lambda().eq(UserEvaluate::getTargetId, sid));
        studentInfoVo.setTeacherEvaluate(defaultEvaluate);
        studentInfoVo.setInternshipEvaluate(defaultEvaluate);
        StuInternship stuInternship = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid));
        if(stuInternship != null) {
            studentInfoVo.setInternshipName(userService.getById(stuInternship.getIid()).getOthername());
        }
        if(list.size() >= 0) {
            list.forEach(item -> {
                /**
                 * 教师评价
                 */
                if (userService.getById(item.getUid()).getType() == 2) {
                    studentInfoVo.setTeacherEvaluate(item.getEvaluate());
                }
                /**
                 * 企业评价
                 */
                if (userService.getById(item.getUid()).getType() == 3) {
                    studentInfoVo.setInternshipEvaluate(item.getEvaluate());
                }
            });
        }


        return R.ok().data("info", studentInfoVo);
    }
}
